package com.zhou.base.components.bs.common.exception;

import cn.hutool.core.util.ObjectUtil;
import com.zhou.base.components.bs.common.exception.base.BaseException;
import com.zhou.base.components.bs.common.exception.model.ParamError;
import com.zhou.base.components.bs.common.model.Response;
import com.zhou.base.components.bs.common.properties.CommonProperties;
import com.zhou.base.components.bs.common.util.StreamUtils;
import feign.FeignException;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.MyBatisSystemException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;
import java.util.List;

import static com.zhou.base.components.bs.common.enums.ResponseEnum.CALLBACK_EXCEPTION;


@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {


    protected CommonProperties commonProperties;
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private HttpServletRequest request;

    public GlobalExceptionHandler(CommonProperties commonProperties) {
        this.commonProperties = commonProperties;
    }


    /**
     * 业务异常
     */
    @ExceptionHandler(BaseException.class)
    public Response<Void> handleServiceException(BaseException e, HttpServletRequest request) {
        log.error(e.getMessage(), e);
        Integer code = e.getCode();
        return ObjectUtil.isNotNull(code) ? Response.fail(code, e.getMessage()) : Response.failMsg(e.getMessage());
    }

    @ExceptionHandler(FeignException.class)
    public Response<Void> handleFeignException(FeignException e, HttpServletRequest request) {
        log.error(e.getMessage(), e);
        Response response;
        if (commonProperties != null && commonProperties.getPrintExceptionDetail()) {
            response = Response.fail(CALLBACK_EXCEPTION.getCode(), e.getMessage());
        } else {
            response = Response.fail(CALLBACK_EXCEPTION.getCode(), CALLBACK_EXCEPTION.getMsg());
        }
        return response;
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler({BindException.class, MethodArgumentNotValidException.class})
    public Response<List<ParamError>> handleBindException(BindException e) {
        log.error(e.getMessage(), e);
        List<ParamError> list = StreamUtils.toList(e.getFieldErrors(), t -> new ParamError(t.getField(), t.getDefaultMessage()));
        return Response.fail(list);
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public Response<List<ParamError>> constraintViolationException(ConstraintViolationException e) {
        log.error(e.getMessage(), e);
        List<ParamError> list = StreamUtils.toList(e.getConstraintViolations(), t -> new ParamError(t.getPropertyPath()
                .toString(), t.getMessage()));
        return Response.fail(list);
    }

    @ExceptionHandler(MissingPathVariableException.class)
    public Response<Void> handleMissingPathVariableException(MissingPathVariableException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求路径中缺少必需的路径变量'{}',发生系统异常.", requestURI, e);
        return Response.failMsg(String.format("请求路径中缺少必需的路径变量[%s]", e.getVariableName()));
    }

    /**
     * 请求参数类型不匹配
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public Response<Void> handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求参数类型不匹配'{}',发生系统异常.", requestURI, e);
        return Response.failMsg(String.format("请求参数类型不匹配，参数[%s]要求类型为：'%s'，但输入值为：'%s'", e.getName(), e.getRequiredType()
                .getName(), e.getValue()));
    }


    /**
     * 请求方式不支持
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Response<Void> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,
                                                              HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',不支持'{}'请求", requestURI, e.getMethod());
        return Response.failMsg(e.getMessage());
    }

    /**
     * 主键或UNIQUE索引，数据重复异常
     */
    @ExceptionHandler(DuplicateKeyException.class)
    public Response<Void> handleDuplicateKeyException(DuplicateKeyException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',数据库中已存在记录'{}'", requestURI, e.getMessage());
        return Response.failMsg("数据库中已存在该记录，请联系管理员确认");
    }

    /**
     * Mybatis系统异常 通用处理
     */
    @ExceptionHandler(MyBatisSystemException.class)
    public Response<Void> handleCannotFindDataSourceException(MyBatisSystemException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        String message = e.getMessage();
        if (message.contains("CannotFindDataSourceException")) {
            log.error("请求地址'{}', 未找到数据源", requestURI);
            return Response.failMsg("未找到数据源，请联系管理员确认");
        }
        log.error("请求地址'{}', Mybatis系统异常", requestURI, e);
        return Response.failMsg(message);
    }

//    @ExceptionHandler(NotPermissionException.class)
//    public Response<Void> handleNotPermissionException(NotPermissionException e, HttpServletRequest request) {
//        String requestURI = request.getRequestURI();
//        log.error("请求地址'{}',权限码校验失败'{}'", requestURI, e.getMessage());
//        return Response.fail(HttpStatus.HTTP_FORBIDDEN, "没有访问权限，请联系管理员授权");
//    }
//
//    /**
//     * 角色权限异常
//     */
//    @ExceptionHandler(NotRoleException.class)
//    public Response<Void> handleNotRoleException(NotRoleException e, HttpServletRequest request) {
//        String requestURI = request.getRequestURI();
//        log.error("请求地址'{}',角色权限校验失败'{}'", requestURI, e.getMessage());
//        return Response.fail(HttpStatus.HTTP_FORBIDDEN, "没有访问权限，请联系管理员授权");
//    }
//
//    /**
//     * 认证失败
//     */
//    @ExceptionHandler(NotLoginException.class)
//    public Response<Void> handleNotLoginException(NotLoginException e, HttpServletRequest request) {
//        String requestURI = request.getRequestURI();
//        log.error("请求地址'{}',认证失败'{}',无法访问系统资源", requestURI, e.getMessage());
//        return Response.fail(HttpStatus.HTTP_UNAUTHORIZED, "认证失败，无法访问系统资源");
//    }

    @ExceptionHandler(RuntimeException.class)
    public Response<Void> handleRuntimeException(RuntimeException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生未知异常.", requestURI, e);
        Response response;
        if (commonProperties != null && commonProperties.getPrintExceptionDetail()) {
            response = Response.failMsg(e.getMessage());
        } else {
            response = Response.failMsg("未知异常");
        }
        return response;
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public Response<Void> handleException(Exception e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生系统异常.", requestURI, e);
        Response response;
        if (commonProperties != null && commonProperties.getPrintExceptionDetail()) {
            response = Response.failMsg(e.getMessage());
        } else {
            response = Response.failMsg("系统异常");
        }
        return response;
    }


}
